//创建和初始化地图函数：

//百度地图API功能
// // 相当于 <script type="text/javascript" src="http://api.map.baidu.com/getscript?v=2.0&ak=U25vSd26q851cuSCjMCXuFkYYemWxvRs&services=&t=20170628183224"></script>
// function loadJScript() {
//     var script = document.createElement("script");
//     script.type = "text/javascript";
//     script.src = "http://api.map.baidu.com/api?v=2.0&ak=2.0&ak=U25vSd26q851cuSCjMCXuFkYYemWxvRs&callback=init";
//     document.body.appendChild(script);
//     $(document.body).append('<script src="http://api.map.baidu.com/library/TextIconOverlay/1.2/src/TextIconOverlay_min.js"><\/script>'); 
// }
// window.onload = loadJScript;  //异步加载地图

function initMap() {
    createMap();//创建地图
    setMapEvent();//设置地图事件
    addMapControl();//向地图添加控件
}
initMap();



//创建地图函数：
function createMap(){
    var map = new BMap.Map("dituContent");//在百度地图容器中创建一个地图
    var Points = new BMap.Point(113.750028,34.718262);//定义一个中心点坐标
    map.centerAndZoom(Points,10);//设定地图的中心点和坐标并将地图显示在地图容器中
    window.map = map;//将map变量存储在全局
}

//地图事件设置函数：
function setMapEvent(){
    map.enableDragging();//启用地图拖拽事件，默认启用(可不写)
    map.enableScrollWheelZoom();//启用地图滚轮放大缩小
    map.enableDoubleClickZoom();//启用鼠标双击放大，默认启用(可不写)
    map.enableKeyboard();//启用键盘上下左右键移动地图
}

//地图控件添加函数：
function addMapControl(){
    //向地图中添加缩放控件
    var ctrl_type = new BMap.MapTypeControl({anchor:BMAP_ANCHOR_TOP_LEFT});
   
    map.addControl(ctrl_type);
    // var ctrl_nav = new BMap.NavigationControl({anchor:BMAP_ANCHOR_BOTTOM_RIGHT,type:BMAP_NAVIGATION_CONTROL_LARGE});
    // map.addControl(ctrl_nav);    
    //向地图中添加比例尺控件
    var ctrl_sca = new BMap.ScaleControl({anchor:BMAP_ANCHOR_BOTTOM_LEFT});
    map.addControl(ctrl_sca);
};


var agentId = $('#ag').attr('key');
var ar = $('#ar').attr('key');
var areaids = ar.split(',');

// websocket
var socket = io('http://lot.iqykj.com:2120');
uid="new";
socket.on('connect',function(){
    socket.emit('login',uid);
});

var markerClusterer2 = null;
var markers2;
// 接收信息
socket.on('new_msg',function(msg){
 
    var rule = /&quot;/g;
    var str_json = msg.replace(rule,'"');
    msg_data = jQuery.parseJSON(str_json);
    if(msg_data.agent_id == agentId||agentId == 1){
        var area_id = new Number(msg_data.area_id);
        if((ar==0)||($.inArray(area_id.toString(),areaids) != -1)){
            if (msg_data.genre !='告警') {
                msg_data.genre = msg_data.genre+"告警";
            }
            if (msg_data.url) {
                if ($('#camera_url').length == 0) {
                    var str = "<object type='application/x-vlc-plugin' id='vlc' events='True'  height='275' pluginspage='http://www.videolan.org' codebase='http://downloads.videolan.org/pub/videolan/vlc-webplugins/2.0.6/npapi-vlc-2.0.6.tar.xz'> <param id='camera_url' name='mrl' value='"+msg_data.url+"'/> <param name='volume' value='50' /> <param name='autoplay' value='true' /> <param name='loop' value='false' /> <param name='fullscreen' value='false' /> </object>";
                    $('#camera').append(str);
                    $('#cam').css('display','block');
                    // $('#cam').removeClass("hide");


                }
            }
            // 防止多图片叠加
            if(markerClusterer2){
                markerClusterer2.clearMarkers();         //此步骤需要
            }
            map.clearOverlays();
            // 图标
            // var redpt =new BMap.Point(smoke_data.lng,smoke_data.lat); // 创建图标位置
            var redpt =new BMap.Point(msg_data.longitude,msg_data.latitude); // 创建图标位置
            var myIcon = new BMap.Icon('/pc/index/img/warning.gif', new BMap.Size(120,120));  // 引入图标
            var marker = new BMap.Marker(redpt,{icon:myIcon}); // 创建标注图标
            markers2 = [];
            markers2.push(marker); // 将标注添加到地图数组中
            markerClusterer2 =new BMapLib.MarkerClusterer(map,{markers:markers2}); // 将图标放入地图

            // 信息窗口
            var sContent = "<div  style=' width:24em; height: 100%; padding: 5px;margin-left: 4px;margin-top: 5px;background-color:#104E8B;  color:#104E8B; border: 1px solid #f1f1f1;border-radius: 5%;' >"+
                "<div  style='background-color: white;height:100%;padding-top:4px'  >"+
                "<p style='font-size: 20px;margin-left: 10px; margin-top: 0px;'>"+msg_data.num+"号"+msg_data.type+"</p>"+
                "<p style='font-size: 14px;margin-left: 10px;margin-top:2px'>报警类型: "+msg_data.genre+"</p>"+
                "<p style='font-size: 14px;margin-left: 10px;'>报警地址:"+msg_data.aname+msg_data.bname+msg_data.rname+msg_data.loc+"</p>"+
                "<p style='font-size: 14px;margin-left: 10px;'>联&nbsp;&nbsp;系&nbsp;&nbsp;人: "+msg_data.user+"</p>"+
                "<p style='font-size: 14px;margin-left: 10px;'>电&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;话: "+msg_data.phone+"</p></div></div>";
            infoWindow = new BMap.InfoWindow(sContent);
            map.openInfoWindow(infoWindow,redpt);
            map.panTo(redpt);
            // 改变报警按钮图标
            $('img[name=jingbao]').attr('src','/pc/index/img/jingbao1.png');                                                     
            // 报警声音
            $('#newMessageDIV').html('<audio autoplay="autoplay" loop=-1><source src="/pc/index/voice/1.WAV"'+
                'type="audio/wav"/><source src="/pc/index/voice/1.mp3" type="audio/mpeg"/></audio>');
                var trs = $("#tbody1 > tr")
                var date = new Date();
                var time = new Date  ().toLocaleString()+' 星期'+'日一二三四五六'.charAt(new Date().getDay  ())
              
             var trs = $("#tbody1 > tr").length;
            if(trs >= 5){
                $('#tbody1 > tr:last-child').remove();
            }
           $('#tbody1').prepend(" <tr style='font-weight:bold;font-size: 1em;' ><td >"+msg_data.genre+"</td><td>"+msg_data.type+"</td><td >"+msg_data.num+"</td><td>"+time+"</td></tr>");
           
            newlist(msg_data.genre,msg_data.type,msg_data.num,time);
        }
    }
});

function newlist(genre,type,num,time){
    var news = jQuery.parseJSON(window.sessionStorage.getItem('news'));
    if(news == null){
        var news = new Array();
    }
        var tmp = {};
        tmp['genre'] = genre;
        tmp['type'] = type;
        tmp['num'] = num;
        tmp['time'] = time;
        news.unshift(tmp);
        window.sessionStorage.setItem("news",JSON.stringify(news));
}


function show(){
    var test = window.sessionStorage.getItem('news');
    session = jQuery.parseJSON(test);
    if(session){
        if(session.length<5){
            var l = session.length;
        }else{
            var l = 5;
        }
        var htmll = '';
        for(var i=0;i<l;i++){
            htmll+="<tr style='font-weight:bold;font-size: 1em;' ><td >"+session[i].genre+"</td><td>"+session[i].type+"</td><td >"+session[i].num+"</td><td>"+session[i].time+"</td></tr>"
        }
           $('#tbody1').append(htmll);   
    }
}
show();

// 遍历span标签
$('.zb').each(function (i) {
    span(i);
});


//  每个span标签
function span (lg)
{
    var num = 0;
    var markers = [];  // 声明地图空数组,用于压入地图图标信息
    $('.zb:eq('+lg+')').click(function ()
    {
        var types;
        var _this = $(this);
        switch (lg)
        {
            case 0:
                // 网关
                types = 'gateway';
                break;
            case 1:
                // 烟感
                types = 'smoke';
                break;
            case 2:
                // 电气
                types = 'electric';
                break;
            case 3:
                // 红外
                types = 'infrared';
                break;
            case 4:
                // 燃气
                types = 'gas';
                break;
            case 5:
                // 呼救
                types = 'help';
                break;
            case 6:
                break;
            case 7:
                break;
            case 8:
                break;
            case 9:
                msg_woran = true;
                break;
            case 10:
                break;
            case 11:
                break;
            default:
                return false;
        }
        if(lg == 9) {
            // 解除警报
            if((_this.find('img').attr('src'))=='/pc/index/img/jingbao1.png'){
                // 移出所有样式
                map.clearOverlays();
                // 移除markers2
                // map.removeOverlay(markers2);
                // 去除'#newMessageDIV'样式 关闭声音
                $('#newMessageDIV').empty();
                markers2.push(0); //将地图数组中的数据写为0
                var markers1 = markers2.slice(markers2.length,0);  
                markerClusterer2.clearMarkers();         //此步骤需要 
                // markerClusterer2 = new BMapLib.MarkerClusterer(map, {markers:markers1}); 清除聚合
                // 改变报警按钮样式
                _this.children().attr('src','/pc/index/img/jingbao.png');
                map.closeInfoWindow();
            }else{
                return false;
            }
        } else {
            // span 标签响应   按钮
            var data_info;
            if(types){
                $.ajax({
                    type:"get",
                    url:"/admin/index/show",
                    async:false,
                    data:{"Types": types},
                    dataType:"json",
                    success:function(str){
                       
                        if(str.length!=0){
                            data_info = str;
                        }else{
                            data_info='';
                        }
                        if(data_info!=''){
                            if(num++ % 2 ===0){
                                /*$.each(point,function(index,value)
                                {   
                                    var redpt =new BMap.Point(value.long,value.lat); // 创建图标位置
                                    var myIcon = new BMap.Icon('/pc/index/img/'+types+'ioc.png', new BMap.Size(44,44));  // 引入图标
                                    var marker = new BMap.Marker(redpt,{icon:myIcon}); // 创建标注
                                    markers.push(marker); // 将标注添加到地图数组中
                                });
                                markerClusterer = new BMapLib.MarkerClusterer(map,{markers:markers}); // 将图标放入地图*/
                                /*var data_info = [[116.417854,39.921988,"<div style=' width:24em; height: 100%; padding: 5px;margin-left: 0px;margin-top: 6px;background-color:#104E8B;  color:#104E8B; border: 1px solid #f1f1f1;border-radius: 5%;' >"+
                                                "<div  style='background-color: white;height:100%;padding-top:4px'  >"+
                                                "<p style='font-size: 20px;margin-left: 10px; margin-top: 0px;'>001号烟感</p>"+
                                                "<p style='font-size: 16px;margin-left: 10px;'>报警地址:<p style='float:right;margin-left: 82px;margin-top: -26px;font-size: 16px'>亳州市谯城区元一小区3号楼4073号楼407</p></p>"+
                                                "<p style='font-size: 16px;margin-left: 10px;'>联&nbsp;&nbsp;系&nbsp;&nbsp;人: 安徽总经理</p>"+
                                                "<p style='font-size: 16px;margin-left: 10px;'>电&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;话: 15238633201</p></div></div>"]];*/
                                
                                for(var i=0;i<data_info.length;i++){
                                    var myIcon = new BMap.Icon('/pc/index/img/'+types+'ioc.png', new BMap.Size(44,44));  // 引入图标
                                    var marker = new BMap.Marker(new BMap.Point(data_info[i]['long'],data_info[i]['lat']),{icon:myIcon});  // 创建标注
                                    var content = data_info[i]['DevEUI'];
                                    addClickHandler(content,marker,types);
                                    markers.push(marker); // 将标注添加到地图数组中  
                                }
                                markerClusterer = new BMapLib.MarkerClusterer(map,{markers:markers}); // 将图标放入地图*/
                                _this.children().attr('src','/pc/index/img/'+types+'1.png');//导航条换图片
                            }else{
                                $.each(data_info,function(index,value)
                                { // 遍历point
                                    map.removeOverlay(markers[index]);
                                    markers.push(0); //将地图数组中的数据写为0
                                }); 
                                var markers1 = markers.slice(markers.length,0);  
                                markerClusterer.clearMarkers();         //此步骤需要  
                                markerClusterer = new BMapLib.MarkerClusterer(map, {markers:markers1});
                                _this.children().attr('src','/pc/index/img/'+types+'.png');
                            }
                        }
                    }
                });
            }
        }
    });
}

function addClickHandler(content,marker,types){
    marker.addEventListener("click",function(e){
        $.ajax({
                    type:"get",
                    url:"/admin/index/info",
                    async:false,
                    data:{'Types': types,'DevEUI':content},
                    dataType:"json",
                    success:function(str){
                        var content = "<div style=' width:24em; height: 100%; padding: 5px;margin-left: 0px;margin-top: 6px;background-color:#104E8B;  color:#104E8B; border: 1px solid #f1f1f1;border-radius: 5%;' >"+
                                       "<div  style='background-color: white;height:100%;padding-top:4px'  >"+
                                       "<p style='font-size: 12px;margin-left: 10px; margin-top: 0px;'>设&nbsp;备&nbsp;类&nbsp;型: "+str.tname+"</p>"+ 
                                       "<p style='font-size: 12px;margin-left: 10px; margin-top: 0px;'>设&nbsp;&nbsp;&nbsp;备&nbsp;&nbsp;&nbsp;&nbsp;ID: "+str.DevEUI+"</p>"+                                                                
                                       "<p style='font-size: 12px;margin-left: 10px;'>地&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;址: "+str.aname+str.bname+str.rname+"</p>"+
                                       "<p style='font-size: 12px;margin-left: 10px;'>区域联系人: "+str.member['area']+"</p>"+
                                       "<p style='font-size: 12px;margin-left: 10px;'>建筑联系人: "+str.member['building']+"</p>"+
                                       "<p style='font-size: 12px;margin-left: 10px;'>房间联系人: "+str.member['room']+"</p></div></div>";

                        openInfo(content,e)
                    }
        });
    });
}

var opts = {
           width : 350,     // 信息窗口宽度
           height:200,     // 信息窗口高度
           // title : "信息窗口" , // 信息窗口标题
           // enableMessage:true//设置允许信息窗发送短息
        };
function openInfo(content,e){
        var p = e.target;
        var point = new BMap.Point(p.getPosition().lng, p.getPosition().lat);
        var infoWindow = new BMap.InfoWindow(content,opts);  // 创建信息窗口对象 
        map.openInfoWindow(infoWindow,point); //开启信息窗口
}